package top.codedance.iotp.common.util;

import java.security.*;

/**
 * 生成公钥和私钥
 */
public class AsymmetricEncryption {
    private static AEncryption aEncryption;

    static {
//        aEncryption = new RSAEncrypt();
        aEncryption = new Sm2Encrypt();
    }

    public static class KeyStringPair {
        private String privateKey;
        private String publicKey;

        public KeyStringPair(String privateKey, String publicKey) {
            this.privateKey = privateKey;
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }
    }

    /**
     * 随机生成密钥对
     *
     * @throws NoSuchAlgorithmException
     */
    public static KeyStringPair genKeyPair() throws Exception {
        return aEncryption.genKeyPair();
    }

    /**
     * RSA公钥加密
     *
     * @param body      加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(byte[] body, String publicKey) throws Exception {
        return aEncryption.encrypt(body, publicKey);
    }

    /**
     * RSA公钥加密
     *
     * @param body      加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String body, String publicKey) throws Exception {
        return aEncryption.encrypt(body, publicKey);
    }

    /**
     * RSA私钥解密
     *
     * @param body       加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(byte[] body, String privateKey) throws Exception {
        return aEncryption.decrypt(body, privateKey);
    }

    /**
     * RSA私钥解密
     *
     * @param body       加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String body, String privateKey) throws Exception {
        return aEncryption.decrypt(body, privateKey);
    }

    /**
     * 用私钥对加密数据进行签名
     *
     * @param encryptedStr
     * @param privateKey
     * @return
     */
    public static String sign(String encryptedStr, String privateKey) {
        return aEncryption.sign(encryptedStr, privateKey);
    }

    /**
     * 校验数字签名
     *
     * @param body
     * @param publicKey
     * @param sign
     * @return 校验成功返回true，失败返回false
     */
    public static boolean verify(String body, String publicKey, String sign) {
        return aEncryption.verify(body, publicKey, sign);
    }
}
